package com.gastudio.gadownloading.slice;

import com.gastudio.gadownloading.ResourceTable;
import com.gastudio.gadownloading.GADownloadingView;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {

  private Runnable mRunnable = new Runnable() {
    @Override
    public void run() {
      mProgress += 10;
      if (!isSuccess && mProgress >= 60) {
        mGADownloadingView.onFail();
      }
      mGADownloadingView.updateProgress(mProgress);
      mHandler.postTask(mRunnable, UPDATE_PROGRESS_DELAY);
    }
  };

  private static final int UPDATE_PROGRESS_DELAY = 500;

  private GADownloadingView mGADownloadingView;
  private Component mShowSuccess, mShowFailed;
  private int mProgress;
  private EventHandler mHandler = new EventHandler(EventRunner.getMainEventRunner());
  private boolean isSuccess = true;

  @Override
  public void onStart(Intent intent) {
    super.onStart(intent);
    super.setUIContent(ResourceTable.Layout_ability_main);
    initViews();
  }

  @Override
  public void onActive() {
    super.onActive();
  }

  private void initViews() {
    mGADownloadingView = (GADownloadingView) findComponentById(ResourceTable.Id_ga_downloading);
    mShowSuccess = findComponentById(ResourceTable.Id_show_success);
    mShowSuccess.setClickedListener(this);
    mShowFailed = findComponentById(ResourceTable.Id_show_failed);
    mShowFailed.setClickedListener(this);
  }

  @Override
  public void onForeground(Intent intent) {
    super.onForeground(intent);
  }

  @Override
  public void onClick(Component component) {
    switch (component.getId()) {
      case ResourceTable.Id_show_success:
        mGADownloadingView.releaseAnimation();
        mHandler.removeTask(mRunnable);
        isSuccess = false;
        mProgress = 0;
        mGADownloadingView.performAnimation();
        mGADownloadingView.updateProgress(0);
        mHandler.postTask(mRunnable, 0);
        break;
      case ResourceTable.Id_show_failed:
        mGADownloadingView.releaseAnimation();
        mHandler.removeTask(mRunnable);
        isSuccess = true;
        mProgress = 0;
        mGADownloadingView.performAnimation();
        mGADownloadingView.updateProgress(0);
        mHandler.postTask(mRunnable, 0);
        break;
    }
  }

  @Override
  protected void onStop() {
    super.onStop();
    mHandler.removeTask(mRunnable);
  }
}
